package com.gimi.cloud.jimi.manage.service.order.impl;

import java.util.*;

import com.gimi.cloud.jimi.dto.user.UserDTO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.gimi.cloud.jimi.common.enums.CommonEnume;
import com.gimi.cloud.jimi.common.enums.ResponseCodeEnum;
import com.gimi.cloud.jimi.common.exception.MsgException;
import com.gimi.cloud.jimi.common.utils.MyBeanUtils;
import com.gimi.cloud.jimi.dao.dao.User.UserDao;
import com.gimi.cloud.jimi.dao.dao.order.OrderCostDao;
import com.gimi.cloud.jimi.dao.dao.order.OrderDao;
import com.gimi.cloud.jimi.dao.dao.order.OrderExpressDao;
import com.gimi.cloud.jimi.dao.dao.order.OrderGoodsDao;
import com.gimi.cloud.jimi.dao.dao.order.OrderInvoiceDao;
import com.gimi.cloud.jimi.dao.dao.order.OrderLogisticsDao;
import com.gimi.cloud.jimi.dao.dao.order.OrderOperDao;
import com.gimi.cloud.jimi.dao.dao.product.ProductSkuDao;
import com.gimi.cloud.jimi.dao.myMapper.core.query.QueryParam;
import com.gimi.cloud.jimi.entity.user.User;
import com.gimi.cloud.jimi.dto.order.OrderCostDTO;
import com.gimi.cloud.jimi.dto.order.OrderDTO;
import com.gimi.cloud.jimi.dto.order.OrderExpressDTO;
import com.gimi.cloud.jimi.dto.order.OrderGoodsDTO;
import com.gimi.cloud.jimi.dto.order.OrderInvoiceDTO;
import com.gimi.cloud.jimi.dto.order.OrderLogisticsDTO;
import com.gimi.cloud.jimi.dto.order.OrderOperDTO;
import com.gimi.cloud.jimi.entity.order.OrderEntity;
import com.gimi.cloud.jimi.entity.order.OrderOperEntity;
import com.gimi.cloud.jimi.entity.product.ProductSkuEntity;
import com.gimi.cloud.jimi.manage.service.order.OrderService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;

@Service
@Transactional(propagation = Propagation.REQUIRED)
public class OrderServiceImpl implements OrderService {
	
	private static Logger logger = LoggerFactory.getLogger(OrderServiceImpl.class);
	
	@Autowired
	private OrderDao orderDao;
	@Autowired
	private OrderOperDao orderOperDao;
	@Autowired
	private UserDao userDao;
	@Autowired
	private ProductSkuDao productSkuDao;
	@Autowired
	private OrderCostDao orderCostDao;
	@Autowired
	private OrderExpressDao orderExpressDao;
	@Autowired
	private OrderGoodsDao orderGoodsDao;
	@Autowired
	private OrderLogisticsDao orderLogisticsDao;
	@Autowired
	private OrderInvoiceDao orderInvoiceDao;
	
	/**
	 * 订单列表(分页)
	 */
	@Override
	public PageInfo<OrderDTO> orderPageListByCondition(OrderDTO orderDTO) throws Exception {
		PageHelper.startPage(orderDTO.getCurrentPage(), orderDTO.getPageSize());
        
        String sql = "SELECT * FROM sh_order WHERE 1=1 AND is_delete = 0 AND order_code LIKE '%'||:orderCode||'%' AND status = :status";
		QueryParam param = new QueryParam();
		param.setSql(sql);
		param.setParamObject(orderDTO);
		List<OrderDTO> datas = orderDao.selectListDTOBySql(param);
		
        PageInfo<OrderDTO> page = new PageInfo<>(datas);
        return page;
	}
	/**
	 * 删除订单
	 */
	@Override
	public void deleteOrder(OrderDTO orderDTO) throws Exception {
		OrderEntity entity = orderDao.selectByPrimaryKey(orderDTO.getOId());
        if (entity != null) {
            //删除订单附属的信息?
            try {
				this.deleteOtherByOrderId(entity.getoId());
			} catch (Exception e) {
				throw new MsgException(ResponseCodeEnum.FAILURE, "订单关联信息删除失败!");
			}
            //删除订单
            entity.setIsDelete(1);//设置删除属性
            int i = orderDao.updateByPrimaryKey(entity);
            if (i <= 0 ) {
				throw new MsgException(ResponseCodeEnum.FAILURE, "订单删除失败!");
			}
        }else {
        	throw new MsgException(ResponseCodeEnum.FAILURE, "没有此条订单记录!");
        }
	}
	//删除级联表信息(假删除)
	private void deleteOtherByOrderId(Integer oId) throws Exception{
		orderCostDao.deleteByOrderId(oId);
		orderExpressDao.deleteByOrderId(oId);
		orderLogisticsDao.deleteByOrderId(oId);
		orderInvoiceDao.deleteByOrderId(oId);
		orderGoodsDao.deleteByOrderId(oId);
		// 重新设置订单中此商品sku库存数量
		List<OrderGoodsDTO> list = orderGoodsDao.getGoodsbyOrderId(oId);
		for (OrderGoodsDTO orderGoodsDTO : list) {
			ProductSkuEntity skuEntity = productSkuDao.selectByPrimaryKey(orderGoodsDTO.getSkuId());
			if (skuEntity != null && skuEntity.getSkuStock()!= null && orderGoodsDTO.getCost() != null) {
				skuEntity.setSkuStock(skuEntity.getSkuStock() + orderGoodsDTO.getCost());
				productSkuDao.updateByPrimaryKey(skuEntity);
			}
		}
	}
	
	/**
	 * 更新订单状态信息
	 */
	@Override
	public void orderStatus(OrderDTO orderDTO) throws Exception {
		OrderEntity entity = orderDao.selectByPrimaryKey(orderDTO.getOId());
        if (entity != null && orderDTO.getStatus() != null) {
        	
        	String status = this.getOrderStatus(orderDTO);//订单原状态
        	if ("A03".equals(status)||"A09".equals(status)||"L05".equals(status)||"L09".equals(status)) {
        		throw new MsgException(ResponseCodeEnum.FAILURE, "已关闭或已完成订单不能改变状态!");
			}
        	
            entity.setStatus(orderDTO.getStatus());
            entity.setBaRemark(orderDTO.getBaRemark());//备注信息
            int i = orderDao.updateByPrimaryKey(entity);
            if (i <= 0 ) {
				throw new MsgException(ResponseCodeEnum.FAILURE, "更新订单状态信息失败!");
			}
            
            //order_oper表增加此订单的操作信息
            OrderOperEntity record = new OrderOperEntity();
            BeanUtils.copyProperties(orderDTO, record);
            record.setoId(entity.getoId());
            record.setOrderCode(entity.getOrderCode());
            record.setStatus(orderDTO.getStatus());
            record.setPayStatus(entity.getPayStatus());
            record.setLogisticsStatus(entity.getLogisticsStatus());
            int result = orderOperDao.baseInsert(record);
            if (result <= 0 ) {
            	throw new MsgException(ResponseCodeEnum.FAILURE, "订单的操作信息写入失败!");
            }
        }else {
        	throw new MsgException(ResponseCodeEnum.FAILURE, "此条订单信息不存在!");
        }
	}
	//单个订单基本信息实体
	@Override
	public OrderDTO getSingleOrderBase(OrderDTO orderDTO) {
		OrderEntity entity = orderDao.selectByPrimaryKey(orderDTO.getOId());
		OrderDTO dto = new OrderDTO();
        MyBeanUtils.copyProperties(entity,dto);
        return dto;
	}
	//更新订单信息
	@Override
	public void updateOrderBase(OrderDTO orderDTO) throws Exception {
		OrderEntity entity = orderDao.selectByPrimaryKey(orderDTO.getOId());
		MyBeanUtils.copyPropertiesIgnoreNull(orderDTO,entity);
        entity.setUpdateTime(new Date());
        int i = orderDao.updateByPrimaryKey(entity);
        if (i <= 0 ) {
        	throw new MsgException(ResponseCodeEnum.FAILURE, "更新订单基本信息失败!");
        }
	}
	/**
	 * 查看订单详细信息
	 * @throws Exception 
	 */
	@Override
	public OrderDTO ShowOrderDetail(OrderDTO orderDTO) throws Exception {
		OrderEntity entity = orderDao.selectByPrimaryKey(orderDTO.getOId());
		
		OrderDTO orderDtoDetail = new OrderDTO();
		MyBeanUtils.copyPropertiesIgnoreNull(entity,orderDtoDetail);
		try {
			//订单状态转换
			String status = CommonEnume.OrderStatus.valueOf(entity.getStatus()).getValue();
			if (status != null) {
				orderDtoDetail.setStatus(status);
			}
			//订单支付方式转换
			String payType = CommonEnume.PayType.valueOf(entity.getPayType()).getValue();
			if (payType != null) {
				orderDtoDetail.setPayType(payType);
			}
			//订单来源方式转换
			String orderSource = CommonEnume.OrderSource.valueOf(entity.getOrderSource()).getValue();
			if (orderSource != null) {
				orderDtoDetail.setOrderSource(orderSource);
			}
			//订单发货状态转换
			String logistics = CommonEnume.LogisticsStatus.valueOf(entity.getLogisticsStatus()).getValue();
			if (logistics != null) {
				orderDtoDetail.setLogisticsStatus(logistics);
			}
		} catch (Exception e) {
			logger.info("数据库订单状态,来源,支付方式等常量枚举信息有误!");
		}
		
		//订单所属用户
		if (entity.getUserId()!=null) {
			User user = userDao.getUserByUserId(entity.getUserId());
			UserDTO userDTO = new UserDTO();
			MyBeanUtils.copyProperties(user,userDTO);
			orderDtoDetail.setUser(userDTO);
		}
		//订单商品列表
		List<OrderGoodsDTO> goodsList = orderGoodsDao.getGoodsbyOrderId(orderDTO.getOId());
		orderDtoDetail.setOrderGoods(goodsList);
		//订单发票
		List<OrderInvoiceDTO> invoiceList = orderInvoiceDao.selectOrderInvoiceByOrder(orderDTO.getOId());
		orderDtoDetail.setOrderInvoice(invoiceList);
		//费用信息
		List<OrderCostDTO> costList = orderCostDao.selectOrderCostByOrder(orderDTO.getOId());
		orderDtoDetail.setOrderCost(costList);
		//配送信息
		List<OrderExpressDTO> expressList = orderExpressDao.selectOrderExpressByOrder(orderDTO.getOId());
		orderDtoDetail.setOrderExpress(expressList);
		//物流信息
		List<OrderLogisticsDTO> logisticsList = orderLogisticsDao.selectOrderLogisticByOrder(orderDTO.getOId());
		orderDtoDetail.setOrderLogistic(logisticsList);
		//操作信息
		List<OrderOperDTO> operList = orderOperDao.getOperListByOid(orderDTO.getOId());
		for (OrderOperDTO orderOperEntity : operList) {
			try {
				//订单支付方式转换
				if ("pay".equals(orderOperEntity.getPayStatus())) {
					orderOperEntity.setPayStatus("已支付");
				}
				if ("nopay".equals(orderOperEntity.getPayStatus())) {
					orderOperEntity.setPayStatus("未支付");
				}
				//订单状态转换
				String status = CommonEnume.OrderStatus.valueOf(orderOperEntity.getStatus()).getValue();
				if (status != null) {
					orderOperEntity.setStatus(status);
				}
				//订单发货状态转换
				String logistics = CommonEnume.LogisticsStatus.valueOf(orderOperEntity.getLogisticsStatus()).getValue();
				if (logistics != null) {
					orderOperEntity.setLogisticsStatus(logistics);
				}
			} catch (Exception e) {
			}
		}
		orderDtoDetail.setOrderOper(operList);
		
		return orderDtoDetail;
	}
	/**
	 * 订单状态
	 */
	@Override
	public String getOrderStatus(OrderDTO orderDTO) throws Exception {
		String status = orderDao.getOrserStatus(orderDTO.getOId());
		if (status == null ) {
        	throw new MsgException(ResponseCodeEnum.FAILURE, "获取订单状态信息失败!");
        }
		return status;
	}

	
	
	
	
	
	
	
	
	

}
